import 'package:flutter/material.dart';
import 'package:flutter_shop/provide/left_category_nav.dart';
import 'package:flutter_shop/service/service_method.dart';
import 'dart:convert';
import '../model/category.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provide/provide.dart';
import 'package:flutter_shop/provide/child_category.dart';
import 'package:flutter_shop/model/categoryGoodsList.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_shop/provide/category_goods_list.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_shop/routers/application.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    Provide.value<LeftCategoryNavProvide>(context).setClickIndex(0,context);
    return Scaffold(
      appBar: AppBar(
        title: Text('商品分类'),
      ),
      body: Container(
        child: Row(
          children: <Widget>[
            LeftCategoryNav(),
            Column(
              children: <Widget>[
                RightCategoryNav(),
                CategoryGoodsList(),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

//左侧大类导航
class LeftCategoryNav extends StatefulWidget {
  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list = [];
  int clickIndex = 0; //记录左侧点击的index

  @override
  void initState() {
//    _getCategory();
//    _getGoodsList(); //初始化默认商品列表第一次进入不空
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Provide<LeftCategoryNavProvide>(builder: (context, child, val) {
      return Container(
        width: ScreenUtil().setWidth(180),
        decoration: BoxDecoration(
          border: Border(
            right: BorderSide(
              color: Colors.black12,
              width: 1,
            ),
          ),
        ),
        child: ListView.builder(
            itemCount: val.categoryNavList.length,
            itemBuilder: (context, index) {
              return _leftInkWell(index, val);
            }),
      );
    });
  }

  Widget _leftInkWell(int index, val) {
    bool isClick = false;
    isClick = (val.clickIndex == index);
    return InkWell(
      onTap: () {
        val.setClickIndex(index, context);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: const EdgeInsets.only(left: 10, top: 20),
        decoration: BoxDecoration(
          color: isClick ? Color.fromRGBO(236, 236, 236, 0.8) : Colors.white,
          border: Border(
            bottom: BorderSide(
              color: Colors.black12,
              width: 1.0,
            ),
          ),
        ),
        child: Text(
          val.categoryNavList[index].mallCategoryName,
          style: TextStyle(
            fontSize: ScreenUtil().setSp(28),
          ),
        ),
      ),
    );
  }

  //Provide化后该方法作废
  void _getCategory() async {
    await request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryModel category = CategoryModel.fromJson(data);
      setState(() {
        list = category.data;
      });

      //将list[0].bxMallSubDto的右侧栏的值传过去，解决刚进入时左侧0点击状态右侧为空的bug
      Provide.value<ChildCategory>(context)
          .setChildCategory(list[0].bxMallSubDto, list[0].mallCategoryId);
    });
  }
  //Provide化后该方法作废
  void _getGoodsList({String categoryId}) async {
    var data = {
      'categoryId': categoryId == null ? '4' : categoryId,
      'categorySubId': '',
      'page': 1,
    };
    await request('getMallGoods', fromData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      Provide.value<CategoryGoodsListProvide>(context)
          .setGoodsList(goodsList.data);
    });
  }
}

//右侧小类的导航栏
class RightCategoryNav extends StatefulWidget {
  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
      builder: (context, child, childCategory) {
        return Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(570),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(color: Colors.black12, width: 1))),
          child: ListView.builder(
            itemCount: childCategory.childCategoryList.length,
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, index) {
              return _rightInkWell(
                  childCategory.childCategoryList[index], index);
            },
          ),
        );
      },
    );
  }

  Widget _rightInkWell(BxMallSubDto item, int index) {
    bool isClick = false;
    isClick = (index == Provide.value<ChildCategory>(context).childIndex)
        ? true
        : false;
    return Container(
      padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
      child: InkWell(
        child: Text(
          item.mallSubName,
          style: TextStyle(
            fontSize: ScreenUtil().setSp(26),
            color: isClick ? Colors.pink : Colors.black, //动态显示高亮
          ),
        ),
        onTap: () {
          Provide.value<ChildCategory>(context)
              .changChildIndex(index, item.mallSubId);
          _getGoodsList(item.mallSubId);
        },
      ),
    );
  }

  void _getGoodsList(String categorySubId) async {
    var data = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': categorySubId,
      'page': 1,
    };
    await request('getMallGoods', fromData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      Provide.value<CategoryGoodsListProvide>(context)
          .setGoodsList(goodsList.data);
    });
  }
}

//分类页商品列表
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  GlobalKey<RefreshFooterState> _footerKey =
      new GlobalKey<RefreshFooterState>();

  var _scrollController = new ScrollController();

  //获取商品列表数据时使用
  var page = 1;

  //List<CategoryListData> categoryGoodsList = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsListProvide>(
      builder: (context, child, data) {
        if (data.goodsList == null) {
          return Expanded(
            child: Center(
              child: Text('商品暂时无货'),
            ),
          );
        } else {
          try {
            if (Provide.value<ChildCategory>(context).page == 1) {
              _scrollController.jumpTo(0.0);
            }
          } catch (e) {
            print('第一次进入');
          }
          return Expanded(
            child: Container(
              width: ScreenUtil().setWidth(570),
              child: EasyRefresh(
                refreshFooter: ClassicsFooter(
                  key: _footerKey,
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  moreInfoColor: Colors.pink,
                  showMore: true,
                  noMoreText: Provide.value<ChildCategory>(context).noMoreText,
                  moreInfo: '加载中...',
                  loadReadyText: '上拉加载',
                ),
                child: ListView.builder(
                  controller: _scrollController,
                  itemCount: data.goodsList.length,
                  itemBuilder: (context, index) {
                    return _goodsItem(context, data.goodsList, index);
                  },
                ),
                loadMore: () async {
                  _getMoreGoodsList();
                },
              ),
            ),
          );
        }
      },
    );
  }

  void _getMoreGoodsList() async {
    Provide.value<ChildCategory>(context).addPage();
    var data = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': Provide.value<ChildCategory>(context).subId,
      'page': Provide.value<ChildCategory>(context).page,
    };
    await request('getMallGoods', fromData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      if (goodsList.data == null) {
        Fluttertoast.showToast(
            msg: '没有更多商品了',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
            textColor: Colors.pink,
            backgroundColor: Colors.white);
        Provide.value<ChildCategory>(context).changeNoMoreText('没有更多');
      } else {
        Provide.value<CategoryGoodsListProvide>(context)
            .setMoreGoodsList(goodsList.data);
      }
    });
  }

  Widget _goodsImage(List goodsList, index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(goodsList[index].image),
    );
  }

  Widget _goodsName(List goodsList, index) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      alignment: Alignment.centerLeft,
      child: Text(
        goodsList[index].goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          fontSize: ScreenUtil().setSp(26),
          color: Colors.black,
        ),
      ),
    );
  }

  Widget _goodsPrice(List goodsList, index) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      padding: EdgeInsets.only(right: 30.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            '价格￥${goodsList[index].presentPrice}',
            style: TextStyle(color: Colors.pink),
          ),
          Text(
            '￥${goodsList[index].oriPrice}',
            style: TextStyle(
              decoration: TextDecoration.lineThrough,
              color: Colors.black12,
            ),
          ),
        ],
      ),
    );
  }

  Widget _goodsItem(context, List goodsList, index) {
    return InkWell(
      onTap: () {
        Application.router
            .navigateTo(context, '/detail?id=${goodsList[index].goodsId}');
        print('点击了');
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            bottom: BorderSide(
              color: Colors.black12,
              width: 1.0,
            ),
          ),
        ),
        child: Row(
          children: <Widget>[
            _goodsImage(goodsList, index),
            Column(
              children: <Widget>[
                _goodsName(goodsList, index),
                _goodsPrice(goodsList, index),
              ],
            ),
          ],
        ),
      ),
    );
  }

/*
  Wrap形式的列表，由于之前home页使用过，项目这里使用ListView
  Widget _wrapList() {
    if (categoryGoodsList.length != 0) {
      List<Widget> listWidget = categoryGoodsList.map((val) {
        return Container(
          width: ScreenUtil().setWidth(280),
          height: ScreenUtil().setHeight(370),
          child: Column(
            children: <Widget>[
              Image.network(val.image),
              Text(
                val.goodsName,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(26),
                  color: Colors.pink,
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Text('价格￥${val.presentPrice}'),
                  Text(
                    '￥${val.oriPrice}',
                    style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      color: Colors.black12,
                    ),
                  ),
                ],
              ),
            ],
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('获取列表为空');
    }
  }*/
}
